package demo.service;

import cn.hutool.core.collection.ListUtil;
import demo.Result;
import demo.entity.Comment;
import demo.entity.Score;
import demo.entity.UserCompany;
import demo.repository.CommentRepository;
import demo.repository.ScoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 评价 Service
 *
 * @author 肖溥博文
 * @version 1.2
 */
@Service
public class CommentService {

    @Autowired
    CommentRepository commentRepository;
    @Autowired
    ScoreRepository scoreRepository;

    /**
     * 按 工作经历 列出所有评价，按时间降序排列
     *
     * @param userCompany 在职信息 id
     * @return 评价对象的数组
     */
    public List<Comment> listComments(UserCompany userCompany) {
        return commentRepository.findCommentsByUserCompanyIdOrderByDateDesc(userCompany.getId());
    }


    public Boolean existsComments(UserCompany userCompany) {
        return !commentRepository.findCommentsByUserCompanyIdOrderByDateDesc(userCompany.getId()).isEmpty();
    }

    /**
     * 添加评价
     *
     * @param comment 评价对象
     * @return 结果对象
     */
    public Result add(Comment comment) {
        comment.setDate(new Date());
        Long commentId = commentRepository.save(comment).getCommentId();
        return Result.success("评价成功", commentId);
    }

    public Result getAverageScoreOfUserCompany(UserCompany userCompany) {
        List<Comment> comments = commentRepository.findCommentsByUserCompanyIdOrderByDateDesc(userCompany.getId());

        if (comments.isEmpty()) {
            return Result.success("该工作经历暂无评价", -1.0);
        }

        double total = 0.0;
        int count = 0;
        for (Comment comment : comments) {
            List<Score> scores = scoreRepository.findScoresByCommentId(comment.getCommentId());
            if (!scores.isEmpty()) {
                count++;
                Long commentTotal = 0L;
                for (Score score : scores) {
                    commentTotal += score.getScore();
                }
                total += ((double) commentTotal) / scores.size();
            }
        }
        total = total / count;

        return Result.success("用户平均评分查找成功", total);
    }
}
